package com.example.cacheredis.service.impl;

import com.example.cacheredis.mapper.DepartmentMapper;
import com.example.cacheredis.pojo.Department;
import com.example.cacheredis.pojo.DepartmentExample;
import com.example.cacheredis.service.DeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired(required = false)
    DepartmentMapper departmentMapper;

    @Autowired
    CacheManager cacheManager;

    Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 注解方式的缓存开发
     *
     * @return
     */
    @Cacheable(cacheNames = "deptList", key = "#root.methodName")
    @Override
    public List<Department> findAllDept() {

        logger.info("查询所有部门");

        return this.departmentMapper.selectByExample(new DepartmentExample());
    }

    /**
     * 使用编码的方式将缓存写入到redis
     *
     * @param departmentId
     * @return
     */
    @Override
    public Department findDeptById(Integer departmentId) {

        Cache deptCache = this.cacheManager.getCache("dept");

        Cache.ValueWrapper valueWrapper = deptCache.get(departmentId);

        if (valueWrapper != null) {
            Department o = (Department) valueWrapper.get();
            logger.info("根据id在redis中查询部门命中\t" + o);
            return o;
        }

        Department department = this.departmentMapper.selectByPrimaryKey(departmentId);

        logger.info("redis中没有该部门id对应的部门，查询数据库");
        /**
         * deptId 作为key
         * department 对象作为value
         */
        if (!ObjectUtils.isEmpty(department)) {
            deptCache.put(department.getDepartmentId(), department);
        }
        return department;
    }
}
